package pers.chy.chyappointmentplatform.Socket;

import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pers.chy.chyappointmentplatform.Config.WebSocketConfig;
import pers.chy.chyappointmentplatform.Mapper.HisMapper.Yjyy_PdjhMapper;
import pers.chy.chyappointmentplatform.Model.NoMapping.ReplyMsgDTO;
import pers.chy.chyappointmentplatform.Service.CallNumberService;

import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

@ServerEndpoint(value = "/Server_PICC", configurator = WebSocketConfig.class)
@Component
public class Server_PICC {




    //
    // 由于websocket是多例的，Spring组件是单例的，所以需以静态方式注入
    //
    private static Yjyy_PdjhMapper yjyy_PdjhMapper;
    @Autowired
    public void setYjyy_PdjhMapper( Yjyy_PdjhMapper yjyy_PdjhMapper) {
        Server_PICC.yjyy_PdjhMapper = yjyy_PdjhMapper;
    }

    private static CallNumberService callNumberService;
    @Autowired
    public void setCallNumberService( CallNumberService callNumberService) {
        Server_PICC.callNumberService = callNumberService;
    }


    @PostConstruct
    public void init() {
        System.out.println("WebSocket 初始化");
    }
    private static Logger log = LoggerFactory.getLogger(Server_PICC.class);
    private static final AtomicInteger OnlineCount = new AtomicInteger(0);
    // concurrent包的线程安全Set，用来存放每个客户端对应的Session对象。
    private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>();


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {

        // 获取IP
        String IP = (String) session.getUserProperties().get("ip");

        //
        SessionSet.add(session);
        int cnt = OnlineCount.incrementAndGet(); // 在线数加1
        log.info("[Socket] 来自{}的连接加入了PICC Server，当前连接数为：{}",IP, cnt);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        SessionSet.remove(session);
        int cnt = OnlineCount.decrementAndGet();
        log.info("[Socket] PICC有连接关闭，当前连接数为：{}", cnt);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     *            客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("[Socket接收数据]：{}",message);


        if ("initData".equals(message)) {

            ReplyMsgDTO replyMsgDTO=new ReplyMsgDTO();
            try{

                // 获取此队列的最新叫号数据（未叫号、已叫号）
                Map dataMap = callNumberService.getLatestData(1);   // 写死 PICC

                // 业务成功
                replyMsgDTO.setStatus(true);
                replyMsgDTO.setDetail(String.format("%s&%s",
                        new Gson().toJson(dataMap.get("wjh")),
                        new Gson().toJson(dataMap.get("yjh"))));

            }catch (Exception ex){
                // 业务失败
                replyMsgDTO.setStatus(false);
                replyMsgDTO.setDetail(ex.getMessage());
                // 异常日志
                log.error("[错误]",ex);
            }
            String replyMsgStr = new Gson().toJson(replyMsgDTO);
//            log.info("[Socket发送数据]："+replyMsgStr);
            log.info("[Socket发送数据]：返回叫号数据（略）");
            // 发送
            SendMessage(session,replyMsgStr);
        }
    }

    /**
     * 出现错误
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("[Socket] 发生错误：{}，Session ID： {}",error.getMessage(),session.getId());
        error.printStackTrace();
    }

    /**
     * 发送消息，实践表明，每次浏览器刷新，session会发生变化。
     * @param session
     * @param message
     */
    public static void SendMessage(Session session, String message) {
        try {
//            session.getBasicRemote().sendText(String.format("%s (From Server，Session ID=%s)",message,session.getId()));
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("[Socket] 发送消息出错：{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 群发消息
     * @param message
     * @throws IOException
     */
    public static void BroadCastInfo(String message) throws IOException {
        log.info("[Socket群发消息]： 向PICC连接主动推送叫号数据（PICC在线数={}）", SessionSet.size());
        for (Session session : SessionSet) {
            if(session.isOpen()){
                SendMessage(session, message);
            }
        }
    }

    /**
     * 指定Session发送消息
     * @param sessionId
     * @param message
     * @throws IOException
     */
    public static void SendMessage(String message,String sessionId) throws IOException {
        Session session = null;
        for (Session s : SessionSet) {
            if(s.getId().equals(sessionId)){
                session = s;
                break;
            }
        }
        if(session!=null){
            SendMessage(session, message);
        }
        else{
            log.warn("没有找到你指定ID的会话：{}",sessionId);
        }
    }

}
